// test_latest_videos.js - 测试最新视频接口
const axios = require('axios');
const fs = require('fs');
const path = require('path');

// 测试配置
const API_BASE_URL = 'http://localhost:3000/api/videos';
const TEST_RESULTS_FILE = path.join(__dirname, 'latest_videos_test_results.json');

// 记录测试结果
const testResults = {
  timestamp: new Date().toISOString(),
  tests: []
};

// 测试结果记录函数
function logTestResult(testName, success, message, data = null) {
  const result = {
    testName,
    success,
    message,
    data
  };
  
  testResults.tests.push(result);
  console.log(`${testName}: ${success ? 'PASS' : 'FAIL'} - ${message}`);
  
  // 保存结果到文件
  fs.writeFileSync(TEST_RESULTS_FILE, JSON.stringify(testResults, null, 2));
  
  return result;
}

// 测试获取最新视频列表（默认参数）
async function testLatestVideosDefaultParams() {
  try {
    const response = await axios.get(`${API_BASE_URL}/latest`);
    
    if (response.status === 200 && response.data.code === 200) {
      // 验证返回的数据结构
      if (response.data.data && 
          Array.isArray(response.data.data.list) &&
          typeof response.data.data.page === 'number' &&
          typeof response.data.data.pageSize === 'number' &&
          typeof response.data.data.total === 'number' &&
          typeof response.data.data.totalPages === 'number') {
        
        // 检查是否按ID降序排序
        const isDescending = response.data.data.list.every((video, index, array) => {
          if (index === array.length - 1) return true;
          return video.id > array[index + 1].id;
        });
        
        if (isDescending) {
          return logTestResult(
            'testLatestVideosDefaultParams',
            true,
            '获取最新视频列表成功（默认参数），并按ID降序排序',
            {
              count: response.data.data.list.length,
              page: response.data.data.page,
              pageSize: response.data.data.pageSize,
              total: response.data.data.total,
              totalPages: response.data.data.totalPages
            }
          );
        } else {
          return logTestResult(
            'testLatestVideosDefaultParams',
            false,
            '获取最新视频列表成功，但未按ID降序排序'
          );
        }
      } else {
        return logTestResult(
          'testLatestVideosDefaultParams',
          false,
          '返回的数据结构不符合预期'
        );
      }
    } else {
      return logTestResult(
        'testLatestVideosDefaultParams',
        false,
        `请求失败，状态码: ${response.status}, 错误码: ${response.data?.code}`
      );
    }
  } catch (error) {
    return logTestResult(
      'testLatestVideosDefaultParams',
      false,
      `请求出错: ${error.message}`
    );
  }
}

// 测试获取最新视频列表（自定义分页参数）
async function testLatestVideosCustomParams() {
  try {
    const page = 2;
    const pageSize = 5;
    const response = await axios.get(`${API_BASE_URL}/latest`, {
      params: { page, pageSize }
    });
    
    if (response.status === 200 && response.data.code === 200) {
      if (response.data.data && 
          response.data.data.page === page &&
          response.data.data.pageSize === pageSize) {
        
        return logTestResult(
          'testLatestVideosCustomParams',
          true,
          '获取最新视频列表成功（自定义分页参数）',
          {
            page: response.data.data.page,
            pageSize: response.data.data.pageSize,
            count: response.data.data.list.length
          }
        );
      } else {
        return logTestResult(
          'testLatestVideosCustomParams',
          false,
          '返回的分页参数不符合请求参数'
        );
      }
    } else {
      return logTestResult(
        'testLatestVideosCustomParams',
        false,
        `请求失败，状态码: ${response.status}, 错误码: ${response.data?.code}`
      );
    }
  } catch (error) {
    return logTestResult(
      'testLatestVideosCustomParams',
      false,
      `请求出错: ${error.message}`
    );
  }
}

// 测试边界情况：无效的页码参数
async function testLatestVideosInvalidPage() {
  try {
    const response = await axios.get(`${API_BASE_URL}/latest`, {
      params: { page: 'invalid', pageSize: 10 }
    });
    
    if (response.status === 200 && response.data.code === 200) {
      // 应该回退到默认值1
      if (response.data.data && response.data.data.page === 1) {
        return logTestResult(
          'testLatestVideosInvalidPage',
          true,
          '无效页码参数自动回退到默认值1',
          { page: response.data.data.page }
        );
      }
    }
    
    return logTestResult(
      'testLatestVideosInvalidPage',
      false,
      '无效页码参数处理不符合预期'
    );
  } catch (error) {
    return logTestResult(
      'testLatestVideosInvalidPage',
      false,
      `请求出错: ${error.message}`
    );
  }
}

// 测试边界情况：无效的每页数量参数
async function testLatestVideosInvalidPageSize() {
  try {
    const response = await axios.get(`${API_BASE_URL}/latest`, {
      params: { page: 1, pageSize: 'invalid' }
    });
    
    if (response.status === 200 && response.data.code === 200) {
      // 应该回退到默认值10
      if (response.data.data && response.data.data.pageSize === 10) {
        return logTestResult(
          'testLatestVideosInvalidPageSize',
          true,
          '无效每页数量参数自动回退到默认值10',
          { pageSize: response.data.data.pageSize }
        );
      }
    }
    
    return logTestResult(
      'testLatestVideosInvalidPageSize',
      false,
      '无效每页数量参数处理不符合预期'
    );
  } catch (error) {
    return logTestResult(
      'testLatestVideosInvalidPageSize',
      false,
      `请求出错: ${error.message}`
    );
  }
}

// 运行所有测试
async function runAllTests() {
  console.log('开始测试最新视频接口...');
  console.log('=============================');
  
  await testLatestVideosDefaultParams();
  await testLatestVideosCustomParams();
  await testLatestVideosInvalidPage();
  await testLatestVideosInvalidPageSize();
  
  console.log('=============================');
  console.log('测试完成！');
  
  // 统计测试结果
  const passed = testResults.tests.filter(test => test.success).length;
  const total = testResults.tests.length;
  
  console.log(`测试结果: ${passed}/${total} 通过`);
  console.log(`测试报告已保存至: ${TEST_RESULTS_FILE}`);
}

// 执行测试
runAllTests();